package com.haust.service.impl;

import com.haust.config.WeChatConfig;
import com.haust.entity.User;
import com.haust.mapper.UserMapper;
import com.haust.service.UserService;
import com.haust.util.HTTPUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

/**
 * @Auther: csp1999
 * @Date: 2020/08/27/19:19
 * @Description: 用户 Service 实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatConfig weChatConfig;

    @Autowired
    private UserMapper userMapper;

    /**
     * 通过code并附带appId appSecret 向微信方索取access_token
     * 并通过 access_token 获得用户基本信息(昵称，地址，头像等) 保存数据到数据库
     * @param code
     * @return
     */
    @Override
    public User saveWeChatUser(String code) {
        // 通过 code 获取 access_tokenURL
        String accessTokenUrl = String.format(
                WeChatConfig.getOpenAccessTokenUrl(),
                weChatConfig.getOpenAppid(),
                weChatConfig.getOpenAppsecret(),
                code);

        // 通过 access_tokenURL 向微信开放平台发送请求, 获取access_token
        Map<String, Object> baseMap = HTTPUtils.doGet(accessTokenUrl);

        if (baseMap == null || baseMap.isEmpty()) {
            return null;
        }

        // 拿到 accessToken
        String accessToken = (String) baseMap.get("access_token");
        String openId = (String) baseMap.get("openid");

        // 通过accessToken 得到向微信开放平台发送 用于获取用户基本信息的请求的url
        String userInfoUrl = String.format(WeChatConfig.getOpenUserInfoUrl(), accessToken, openId);

        // 获取access_token
        Map<String, Object> baseUserMap = HTTPUtils.doGet(userInfoUrl);

        if (baseUserMap == null || baseUserMap.isEmpty()) {
            return null;
        }
        // 拿到用户基本信息
        String nickname = (String) baseUserMap.get("nickname");// 微信用户名
        //System.out.println(baseUserMap.get("sex"));
        //Double sexTemp = (Double) baseUserMap.get("sex");// 微信用户性别
        //System.out.println(sexTemp);
        //int sex = sexTemp.intValue();// Double => Integer
        String province = (String) baseUserMap.get("province");// 微信用户所在省
        String city = (String) baseUserMap.get("city");// 微信用户所在市
        String country = (String) baseUserMap.get("country");// 微信用户所在国家
        String headimgurl = (String) baseUserMap.get("headimgurl");// 微信用户头像

        StringBuilder builder = new StringBuilder(country).append("||").append(province).append("||").append(city);
        String finalAddress = builder.toString();

        try {
            //解决中文乱码
            nickname = new String(nickname.getBytes("ISO-8859-1"), "UTF-8");
            finalAddress = new String(finalAddress.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        User user = new User();
        user.setName(nickname).setHeadImg(headimgurl).setCity(finalAddress).setOpenid(openId).setSex(0).setCreateTime(new Date());

        User findUser = userMapper.findByUserOpenid(openId);
        if (findUser != null) { //如果数据库中已经有该微信用户信息，更新微信用户最新基本信息，并直接返回即可
            userMapper.updateUser(user);
            return user;
        }// 否则继续往下执行

        userMapper.saveUser(user);// 保存用户信息
        return user;
    }
}
